<!--
 * @Author: hpc(hepch)
 * @Date: 2021-06-15 13:41:36
 * @LastEditors: 杨光辉(GerhardYang)
 * @LastEditTime: 2021-08-09 09:18:46
 * @Description: content
 * @Copyright: 超图软件华中平台客户中心 (SuperMap Software Co., Ltd. -Central China Platform)
-->
<template>
  <div id="Mark">
    <a-card title="点击跳转至记录位置" style="width: 300px" size="small">
      <a slot="extra" href="#" title="关闭" @click="onClose">
        <a-icon type="close" />
      </a>
      <h6 v-show="!marklist || !marklist.length">没有您的标记记录</h6>
      <p></p>
      <div
        class="booktag"
        style="margin-top: 0px"
        v-show="marklist && marklist.length"
      >
        <a-tag
          style="margin-top: 0px"
          :color="color()"
          v-for="item in marklist"
          :key="item.id"
          @click="toMarkerLocation(item.id)"
          closable
          @close="() => removeMarkerFromList(item.id)"
          >{{ item.name }}
        </a-tag>
      </div>
    </a-card>
  </div>
</template>

<script>
import L from "leaflet";
import services from "@/services/api.js";
export default {
  data() {
    return {
      markerid: 0,
      title: "",
      marklist: [],
    };
  },
  computed: {
    markelabelGroup() {
      return this.$store.state.markelabelGroup;
    },
    map() {
      return this.$store.state.map;
    },
    userName() {
      return this.$store.state.userName;
    },
  },
  mounted() {
    this.getUerName();
    var self = this;
    window.removeMarker = (id) => {
      if (!this.userName) {
        this.removeMarkFromBrower(id);
        return;
      }
      let willRemoveOne = this.marklist.filter((item) => item.id == id);
      let param = {
        id: willRemoveOne[0].id,
      };
      services.removeBookMark(param).then((res) => {
        res.success == true
          ? (this.queryMark(), this.$message.success("移除成功"))
          : (this.$message.warning("移除失败"),
            (this.marklist = [...this.marklist]));
      });

      // this.title = document.getElementById("markertitle-divid").value;
    };
    window.editMark = (e, id) => {
      if (e) {
        let evt = window.event || e;
        if (evt.keyCode === 13) {
          self.title = document.getElementById("markertitle-divid").value;

          if (self.title != "") {
            self.editMark(id);
          }
          self.title = "";
        }
      } else {
        self.title = document.getElementById("markertitle-divid").value;

        if (self.title != "") {
          self.editMark(id);
        }

        self.title = "";
      }
    };
    window.marktitle = (e) => {
      if (e) {
        let evt = window.event || e;
        if (evt.keyCode === 13) {
          self.title = document.getElementById("markertitle-divid").value;
          self.marker.unbindTooltip();
          if (self.title != "") {
            console.log("这是要保存到标注", self.marker);
            self.saveMark(self.title, self.marker._latlng);
          }
          self.title = "";
        }
      } else {
        self.title = document.getElementById("markertitle-divid").value;
        self.marker.unbindTooltip();
        if (self.title != "") {
          console.log("这是要保存到标注", self.marker);
          self.saveMark(self.title, self.marker._latlng);
        }
        self.title = "";
      }
    };
  },
  methods: {
    color() {
      return (
        "#" +
        ("00000" + ((Math.random() * 0x1000000) << 0).toString(16)).substr(-6)
      );
    },
    onClose() {
      this.$parent.isMark = false;
    },
    toMarkerLocation(id) {
      console.log(id);
      let markitem = this.marklist.filter((item) => item.id == id)[0];
      console.log(markitem);
      if (markitem && markitem.data) {
        let latlng = markitem.data.latlng;
        this.map.setView([latlng.lat, latlng.lng], 15);
      } else {
        this.$message.warning("此标记未记录到位置信息");
      }
    },
    removeMarkerFromList(id) {
      window.removeMarker(id);
    },
    removeMarkFromBrower(id) {
      this.marklist = this.marklist.filter((item) => item.id != id);
      localStorage.setItem("MapMarks", JSON.stringify(this.marklist));
      this.queryMarkFromBrower("second");
      this.$message.success("移除成功");
    },
    queryMarkFromBrower(str) {
      let self = this;
      this.marklist = [];
      this.markelabelGroup.clearLayers();
      this.marklist = JSON.parse(localStorage.getItem("MapMarks"));
      if (this.marklist == undefined || this.marklist == null) {
        this.marklist = [];
      }

      this.marklist.map((item) => {
        self.marker2map(item);
      });
      if (this.marklist.length && !str) {
        this.$message.info("您未登录，已帮您获取本地标注记录");
      }
    },
    async queryMark() {
      let param = {
        userName: this.userName,
        pageNo: 1,
        pageSize: 100,
      };
      this.markelabelGroup.clearLayers();
      this.marklist = [];
      this.userName
        ? await services.querybookMark(param).then((res) => {
            let userNameBookList = res.result.records.filter(
              (item) =>
                item.userName == this.userName &&
                item.name &&
                item.name.indexOf("标注") > -1
            );
            let aMark;
            userNameBookList.map((item) => {
              item.data && item.data != ""
                ? ((aMark = JSON.parse(item.data)),
                  (aMark.id = item.id),
                  this.marklist.push(aMark))
                : "";
            });
            this.marklist.map((item) => {
              this.marker2map(item);
            });
          })
        : this.queryMarkFromBrower();
    },
    marker2map(item) {
      let self = this;
      let icon = L.icon({
        iconSize: [35, 40],
        iconAnchor: [19, 13],
        iconUrl: `./img/icons/tuding.png`,
      });
      L.marker([item.data.latlng.lat, item.data.latlng.lng], {
        icon: icon,
      })
        .bindPopup((marker) => {
          self.marker = marker;
          return `名称: <input type="text" id="markertitle-divid"   value='${
            item.name
          }' onkeydown="window.editMark(Event,${
            item.id
          })" >  <button style="background-color: #1a90fd;
    color: #fffafa;" onclick="window.editMark(${null},${
            item.id
          })">修改</button> <button style="background-color: #1a90fd;
    color: #fffafa;" onclick="window.removeMarker(${item.id})">删除</button>`;
        })
        .bindTooltip(`${item.name}`, {
          permanent: true,
          offset: L.point(0, 20),
          direction: "right",
        })
        .addTo(this.markelabelGroup)
        .openTooltip();
    },
    editMarkfromBerwer(id) {
      let queryMark = this.marklist.filter((item) => item.id == id)[0];
      if (queryMark) {
        queryMark.name = this.title;
        this.Mark = queryMark;
        localStorage.setItem("MapMarks", JSON.stringify(this.marklist));
        this.queryMarkFromBrower("second");
        this.$message.success("修改成功");
        document
          .getElementsByClassName("leaflet-popup-close-button")[0]
          .click();
      }
    },
    async editMark(id) {
      let queryMark = this.marklist.filter((item) => item.id == id)[0];
      if (!this.userName) {
        this.editMarkfromBerwer(id);
        return;
      }
      if (queryMark) {
        queryMark.name = this.title;
        this.Mark = queryMark;

        let param = {
          id: queryMark.id,
        };
        await services.removeBookMark(param).then((res) => {
          res.success == true
            ? ((param = {
                data: JSON.stringify(this.Mark),
                id: id,
                name: "标注",
                userName: this.userName,
              }),
              services.savebookMark(param).then((res) => {
                res.success == true
                  ? (this.queryMark(),
                    this.$message.success("修改成功"),
                    document
                      .getElementsByClassName("leaflet-popup-close-button")[0]
                      .click())
                  : this.$message.error("修改失败");
              }))
            : (this.$message.warning("修改失败"),
              (this.marklist = [...this.marklist]));
        });
      }
    },
    saveMarkToBrower() {
      this.marklist.push(this.Mark);
      localStorage.setItem("MapMarks", JSON.stringify(this.marklist));
      this.queryMarkFromBrower();
      this.$message.success("成功添加记录至浏览器缓存");
      document.getElementsByClassName("leaflet-popup-close-button")[0].click();
    },
    saveMark(title, latlng) {
      if (title && title !== "") {
        title = title.replace(/\s+/g, "");
        this.Mark = {
          id: this.marklist.length,
          name: title,
          data: {
            latlng: latlng,
          },
        };
        console.log("书签信息", this.Mark);
        let param = {
          data: JSON.stringify(this.Mark),
          userName: this.userName,
          name: "标注",
        };
        this.userName
          ? services.savebookMark(param).then((res) => {
              res.success == true
                ? (this.queryMark(),
                  this.$message.success("添加成功"),
                  document
                    .getElementsByClassName("leaflet-popup-close-button")[0]
                    .click())
                : this.$message.error("添加失败");
            })
          : this.saveMarkToBrower();
      } else {
        this.$message.info("名称不能为空");
        return;
      }
    },

    addmarkerToMap(latlng) {
      //L.tooltip({sticky:true}).addTo(this.map)

      let self = this;
      let icon = L.icon({
        iconSize: [35, 40],
        iconAnchor: [19, 13],
        iconUrl: `./img/icons/tuding.png`,
      });
      this.marker = L.marker(latlng, { icon: icon, draggable: true })
        .bindPopup((marker) => {
          self.marker = marker;
          return `名称: <input type="text" id="markertitle-divid" onkeydown="window.marktitle(Event)" >  <button style="background-color: #1a90fd;
    color: #fffafa;" onclick="window.marktitle()">保存</button>`;
        })
        .addTo(this.markelabelGroup);
      L.popup()
        .setLatLng(latlng)
        .setContent(
          `名称: <input type="text" id="markertitle-divid" onkeydown="window.marktitle(Event)" >  <button style="background-color: #1a90fd;
    color: #fffafa;" onclick="window.marktitle()">保存</button>`
        )
        .openOn(this.map);
    },
    clearMarker() {
      this.markelabelGroup.clearLayers();
    },
    async getUerName() {
      await services
        .getUserName()
        .then((res) => {
          console.log("用户信息", res);
          res.userName && res.userName != null && res.userName !== "GUEST"
            ? (this.$store.commit("setUserName", res.userName),
              this.queryMark())
            : this.queryMark();
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
};
</script>

<style></style>
